//获取应用实例
const app = getApp()
const genAudioUrl = "https://api.ai.qq.com/fcgi-bin/aai/aai_tts";
const WxUtil = require('../../../utils/WxUtil.js')
const questionUtil = require('../../../utils/questionUtil.js')
const innerAudioContext = wx.createInnerAudioContext();
//问题个数
const questionNum = 10;
const db = wx.cloud.database();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    btn_disabled:false,
    show:false, //加载出题目之前，不显示页面。
    showRight:false,
    showError: false,
    audio:null,
    buttonTitle: "下一题",
    checked:false,
    percent: 100/questionNum,
    question_idx: 1,
    questionList: [],
    rightAnswer:null,
    questionNum: questionNum,
    option_a:"default",
    option_b: "default",
    option_c: "default",
    option_d: "default"
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    let that = this;
    //1到14随机
    var page = Math.floor(Math.random() *14)+1;
    wx.showLoading();

    //调用分页云函数
    wx.cloud.callFunction({
      name: 'pagination',
      data: {
        dbName: 'word_question_bw',
        pageIndex: page,
        pageSize: questionNum,
        filter: null
      },
      success(res) {
        var questionList = res.result.data;
        //查出第一题的正确答案：
        var rightAnswer = questionList[0].OPTION_RIGHT;

        that.setData({
          show: true,
          rightAnswer: that.parseRightNum(rightAnswer),
          questionList: questionList
        });
        wx.hideLoading();

        //生成音频
        that.generateAudio();

      },
      fail() {
        
      }
    });
  },
  nextQuestion: function () {
    let that = this;

    //禁用按钮
    this.setData({ btn_disabled: true });
    //当前题的序号（还未跳至下一题。）
    var idx = this.data.question_idx;

    //该题用户选择的
    var user_select = this.data.questionList[idx - 1].user_select;
    //该题正确答案
    var right_option = this.data.questionList[idx - 1].OPTION_RIGHT;
    if (user_select == right_option)
    {
      this.setData({showRight:true});
    }else
    {
      this.setData({ showError: true });
    }

    //点亮正确答案
    this.lightOptoin();


    //题做完了
    if (idx >= questionNum) {
      //let data = JSON.stringify(this.data.questionList);
      //console.info("===data==" + data);
      app.globalData.userQuetionList.length = 0;
      app.globalData.userQuetionList = questionUtil.bw2Question(this.data.questionList);
      setTimeout(function () {
        wx.redirectTo({
          url: '/pages/tools/result/result'
        });
      },1500);

      return ;
    }
    idx++;
    var percent = (100 / questionNum) * idx;
    var buttonTitle= "下一题";

    if (idx == questionNum)
    {
      buttonTitle = "提交";
    }

    var rightAnswer = this.data.questionList[idx - 1].OPTION_RIGHT;

    setTimeout(function(){

      //设data,页面跳至下一题。
      that.setData({
        btn_disabled:false,
        buttonTitle: buttonTitle,
        question_idx: idx,
        percent: percent,
        checked: false,
        showRight: false,
        showError: false,
        rightAnswer: that.parseRightNum(rightAnswer),
        option_a: "default",
        option_b: "default",
        option_c: "default",
        option_d: "default"
      });

      //生成音频
      that.generateAudio();
    }, 2000);
    
  },

  /**
   * 选择答案
   */
  selectOption: function (e) {

    //记录用户选择的答案
    var user_select = e.currentTarget.dataset.id;
    var question_idx = this.data.question_idx;
    this.data.questionList[question_idx - 1].user_select = parseInt(user_select);

  },

  //点亮正确选项
  lightOptoin:function()
  {
    //当前题的序号（还未跳至下一题。）
    var idx = this.data.question_idx;
    
    //该题正确答案
    var right_option = this.data.questionList[idx - 1].OPTION_RIGHT;
    var rightAnswer = "rightOption";
    if (right_option==1) {
      this.setData({ option_a: rightAnswer});
    }
    if (right_option == 2) {
      this.setData({ option_b: rightAnswer });
    }
    if (right_option == 3) {
      this.setData({ option_c: rightAnswer });
    }
    if (right_option == 4) {
      this.setData({ option_d: rightAnswer });
    }
  },
  generateAudio() {
    let that = this;
    let question_idx = this.data.question_idx;
    let word = this.data.questionList[question_idx - 1].WORD;


    //在单词或词组中没有查到，则到词根里面看看。
    db.collection("words").where({
      word: word
    }).get().then(res => {
      if (res.data.length > 0) {
        let wordDB = res.data[0];
        let audio = wordDB.audio_us;
        if(null==audio)
        {
          audio=wordDB.audio;
        }
        
        that.setData({
          audio: audio
        });
        that.playAudio();
      }
    });

  },

  //生成音频(腾讯接口))
  generateAudio_wx() {
    let that = this;
    let question_idx = this.data.question_idx;
    let text = this.data.questionList[question_idx - 1].WORD;
    let app_id = app.globalData.aiAppId;
    let time_stamp = parseInt(new Date().getTime() / 1000);
    let nonce_str = WxUtil.getRandStr();

    let params = {
      app_id: app_id,
      time_stamp: time_stamp,
      nonce_str: nonce_str,
      text: text,
      speaker: 6,
      format: 2,
      volume: 0,
      speed: 100,
      aht: 0,
      apc: 58
    }

    let sign = WxUtil.getReqSign(params);
    params.sign = sign;

    wx.request({
      url: genAudioUrl,
      method: 'post',
      data: params,
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {

        that.setData({
          audio: res.data.data.speech
        });

        that.playAudio();

      },
      fail: function (error) {
        console.error(error)
      }
    })
  },

  //播放音频
  playAudio() {
    // innerAudioContext.src = "data:audio/wav;base64," + this.data.audio;
    // innerAudioContext.play();
    //var src = "data:audio/x-wav;base64," + this.data.audio;
    
    var src = this.data.audio;
    wx.playBackgroundAudio({
      dataUrl: src,
      title:"播放音频",
      success: (res) => {
      },
      fail: (res) => {
        console.info("===fail==fail");
        console.info(res);
      },
      complete: function (res) {
        console.info(res);
      }
    })
  },

  //转化1234为ABCD
  parseRightNum: function (num) {
    var right = "";
    switch (num) {
      case 1:
        right = "A";
        break;
      case 2:
        right = "B";
        break;
      case 3:
        right = "C";
        break;
      case 4:
        right = "D";
        break;
      case 5:
        right = "E";
        break;
      default:
    }

    return right;
  }

})